package com.cloudcc.mobile.search;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.model.MenuModel;
import com.cloudcc.cloudframe.model.MenuTabModel;
import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.search.adapter.SearchlistAdapter;
import com.cloudcc.mobile.util.CharacterParser;
import com.cloudcc.mobile.view.activity.BeauInfoActivity;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.weight.ClearEditText;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.mypage.model.SearchResultCount;
import com.mypage.model.SearchResultEntity;
import com.mypage.model.SearchhestroyResultEntity;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


public class SearchActivity extends BaseActivity {
    private ListView search_list;
    private TextView search_right, search_sousuo, search_neirong;
    private ClearEditText et_search_content;
    private ImageView search_back, search_no;
    private ExpandableListView search_ExpandableListViewlist;
    protected CharacterParser characterParser;
    private String sousuo = "";
    private SearchResultEntity searchResultEntity;
    private LayoutInflater inflater;
    private LinearLayout footView;

    //没有历史记录记得不要显示搜索
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initview();
        addlistener();
        initdata();
        initFilter();

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_search;
    }

    public void close(){

        InputMethodManager imm = (InputMethodManager)getSystemService(mContext.INPUT_METHOD_SERVICE);
        boolean is = imm .isActive();
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),0);
//		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

    }
    private void addlistener() {
        search_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //请求接口 传递数据
                if (sousuo.length() >= 2) {
                    listCount.clear();
                    close();
                    requestdata();
                } else {
                    Toast.makeText(SearchActivity.this, getResources().getString(R.string.searchtishi), 1).show();
                }

            }
        });
        search_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        footView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击调用接口
                if (sousuo.length() >= 2) {
                    listCount.clear();
                    requestdata();
                } else {
                    Toast.makeText(SearchActivity.this, getResources().getString(R.string.searchtishi), 1).show();
                }
            }
        });
    }

    MyexpandableListAdapter exAdapter = null;
    private String prefix;

    public void requestdata() {
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance()
                .getServerBinding());
        params.addBodyParameter("serviceName", "globalSearch");

        params.addBodyParameter("pageNUM", "1");
        params.addBodyParameter("pageSize", "3");
        params.addBodyParameter("searchKeyWord", sousuo);
        Log.d("request",
                "链接" + UrlManager.getInterfaceUrl()
                        + GsonUtil.Object2Json(params));
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        Log.d("qingqiushibai", "Failure。。。"
                                + arg1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        String result = arg0.result;
                        Log.d("sousuoshuju", result);
                        try {
                            Gson gson = new Gson();
                            SearchResultEntity ss = gson.fromJson(result,
                                    SearchResultEntity.class);
                            searchResultEntity = ss;

                            //解析数据
                            if (ss.data.size() > 0) {
                                search_ExpandableListViewlist.setVisibility(View.VISIBLE);
                                search_list.setVisibility(View.GONE);
                                search_no.setVisibility(View.GONE);
                                search_neirong.setVisibility(View.GONE);
                                exAdapter = new MyexpandableListAdapter(SearchActivity.this);
                                search_ExpandableListViewlist.setAdapter(exAdapter);
                                for (int i = 0; i < ss.data.size(); i++) {
                                    search_ExpandableListViewlist.expandGroup(i);
                                }
                                for (int i = 0; i < ss.data.size(); i++) {
                                    prefix = ss.data.get(i).prefix;
                                    requestCount(prefix);
                                }
                            } else {
                                search_no.setVisibility(View.VISIBLE);
                                search_neirong.setVisibility(View.VISIBLE);
                                search_ExpandableListViewlist.setVisibility(View.GONE);
                                search_list.setVisibility(View.GONE);
                            }

                            close();
                        } catch (Exception ex) {

                        }
                    }
                });
    }

    List<Map<String,String>> listCount = new ArrayList<>();

    public void requestCount(String prefix) {
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("serviceName", "searchRecordCount");
        params.addBodyParameter("binding", RunTimeManager.getInstance()
                .getServerBinding());
        params.addBodyParameter("searchKeyWord", sousuo);
        params.addBodyParameter("prefix", prefix);
        params.addBodyParameter("count", "51");
        Log.d("request",
                "链接" + UrlManager.getInterfaceUrl()
                        + GsonUtil.Object2Json(params));
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        Log.d("qingqiushibai", "Failure。。。"
                                + arg1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        String result = arg0.result;
                        Log.d("soucount", result);
                        Gson gson = new Gson();
                        SearchResultCount ss = gson.fromJson(result,
                                SearchResultCount.class);
                        Map<String,String> stringStringMap = new HashMap<String, String>();
                        stringStringMap.put(ss.data.prefix,ss.data.count);
                        listCount.add(stringStringMap);
                        exAdapter.notifyDataSetChanged();
                    }
                });
    }

    private void initview() {
        inflater = LayoutInflater.from(SearchActivity.this);
        footView = (LinearLayout) inflater.inflate(R.layout.search_footview, null);//得到尾部的布局
        footView.setVisibility(View.GONE);
        search_sousuo = (TextView) footView.findViewById(R.id.search_sousuo);
        //历史记录的listview
        search_list = (ListView) findViewById(R.id.search_list);

        //搜索的search_ExpandableListViewlist
        search_ExpandableListViewlist = (ExpandableListView) findViewById(R.id.search_ExpandableListViewlist);
        search_ExpandableListViewlist.setGroupIndicator(null);
        //搜索
        search_right = (TextView) findViewById(R.id.search_right);
        //输入框
        et_search_content = (ClearEditText) findViewById(R.id.et_search_content);
        //返回
        search_back = (ImageView) findViewById(R.id.search_back);
        // 搜索最下面
        //        search_sousuo = (TextView) findViewById(R.id.search_sousuo);
        //没有数据的图片
        search_no = (ImageView) findViewById(R.id.search_no);
        search_neirong = (TextView) findViewById(R.id.search_neirong);
        et_search_content.setPadding(12,0,20,0);
        //        search_list.addFooterView(footView);
        //        search_list.removeFooterView(footView);
    }

    private SearchlistAdapter adapter;
    private String et_search_contenttext;
    private List<MenuModel> menusend;// 所有的
    private List<MenuTabModel> listHestroyold;// 历史
    public List<MenuTabModel> lishilist;//筛选之后的
    public List<MenuTabModel> listHestroy;//請求歷史數據
    public List<MenuTabModel> listHestroynow;//歷史數據篩選之後
    private Context context;

    private void initdata() {
        et_search_contenttext = et_search_content.getText().toString().trim();
        menusend = (List<MenuModel>) getIntent().getSerializableExtra(
                "sort.filter");
        listHestroy = new ArrayList<>();
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance()
                .getServerBinding());
        params.addBodyParameter("serviceName", "getRecentItems");

        params.addBodyParameter("pageNUM", "1");
        params.addBodyParameter("pageSize", "10");
        Log.d("request",
                "链接" + UrlManager.getInterfaceUrl()
                        + GsonUtil.Object2Json(params));
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        Log.d("qingqiushibai", "Failure。。。"
                                + arg1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        String result = arg0.result;
                        Log.d("request", "success。。。"
                                + result);
                        try {
                            Gson gson = new Gson();
                            SearchhestroyResultEntity ss = gson.fromJson(result,
                                    SearchhestroyResultEntity.class);
                            if (ss.data.size() > 0) {
                                search_list.setVisibility(View.VISIBLE);
                                search_no.setVisibility(View.GONE);
                                search_neirong.setVisibility(View.GONE);
                                search_ExpandableListViewlist.setVisibility(View.GONE);
                                //                            search_sousuo.setVisibility(View.VISIBLE);
                                for (int i = 0; i < ss.data.size(); i++) {
                                    MenuTabModel menuModel = new MenuTabModel();
                                    menuModel.search_name = ss.data.get(i).label;
                                    menuModel.search_name1 = ss.data.get(i).recordname;
                                    menuModel.search_nameID = ss.data.get(i).recordid;
                                    menuModel.prefix = ss.data.get(i).prefix;
                                    listHestroy.add(menuModel);
                                }

                                lishilist = new ArrayList<MenuTabModel>();
                                if (adapter == null) {
                                    adapter = new SearchlistAdapter(SearchActivity.this, lishilist, listHestroy, sousuo);
                                    search_list.setAdapter(adapter);
                                    lishilist.clear();
                                } else {
                                    adapter.changeData(lishilist, listHestroy, sousuo);
                                    lishilist.clear();
                                }
                            } else {
                                search_list.setVisibility(View.GONE);
                                search_no.setVisibility(View.VISIBLE);
                                search_neirong.setVisibility(View.VISIBLE);
                                search_ExpandableListViewlist.setVisibility(View.GONE);
                            }

                        } catch (Exception ex) {
                        }
                    }
                });


    }

    int isfirst = 1;

    private void initFilter() {
        characterParser = CharacterParser.getInstance();
        // 根据输入框输入值的改变来过滤搜索
        et_search_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                sousuo = s.toString();
                if ("".equals(sousuo)) {
                    et_search_content.setGravity(Gravity.CENTER);
                    search_list.removeFooterView(footView);
                    isfirst = 1;
                    //                    footView.setVisibility(View.GONE);
                    lishilist = new ArrayList<MenuTabModel>();
                    if (listHestroy.size() > 0) {
                        search_list.setVisibility(View.VISIBLE);
                        search_ExpandableListViewlist.setVisibility(View.GONE);
                        search_no.setVisibility(View.GONE);
                        search_neirong.setVisibility(View.GONE);
                    }
                    if (adapter == null) {

                        adapter = new SearchlistAdapter(SearchActivity.this, lishilist, listHestroy, sousuo);
                        search_list.setAdapter(adapter);
                        //                        lishilist.clear();
                        //                        listHestroynow.clear();
                    } else {
                        adapter.changeData(lishilist, listHestroy, sousuo);
                        //                        lishilist.clear();
                        //                        listHestroy.clear();
                    }
                } else {
                    if (isfirst == 1) {
                        search_list.addFooterView(footView);
                    }
                    et_search_content.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
                    filterData(s.toString());
                    search_sousuo.setText("搜索“" + sousuo + "”");
                    footView.setVisibility(View.VISIBLE);
                    isfirst++;
                }

            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    private void filterData(String filterStr) {
        lishilist = new ArrayList<>();
        listHestroynow = new ArrayList<>();
        //遍历查找符合数据
        if (menusend.size() > 0) {
            for (int i = 0; i < menusend.size(); i++) {
                for (int j = 0; j < menusend.get(i).tab.size(); j++) {
                    if ((filterStr.length() > 0) && (menusend.get(i).tab.get(j).tabName.contains(filterStr))) {
                        String id = menusend.get(i).tab.get(j).search_nameID;
                        String id1 = menusend.get(i).tab.get(j).search_name;
                        String id2 = menusend.get(i).tab.get(j).search_name1;
                        String id3 = menusend.get(i).tab.get(j).objId;
                        String id4 = menusend.get(i).tab.get(j).tab_name;
                        String id5 = menusend.get(i).tab.get(j).tabStyle;
                        menusend.get(i).tab.get(j).isduixiang = true;
                        lishilist.add(menusend.get(i).tab.get(j));
                    }
                    //                    if(menusend.get(i).tab.get(j).tabName != null
                    //                            && (menusend.get(i).tab.get(j).tabName.indexOf(filterStr.toString().toLowerCase()) != -1 || characterParser
                    //                            .getSelling(menusend.get(i).tab.get(j).tabName).startsWith(
                    //                                    filterStr.toString()))){
                    //                        menusend.get(i).tab.get(j).isduixiang = true;
                    //                        lishilist.add(menusend.get(i).tab.get(j));
                    //
                    //                    }


                }
            }
        }
        if (listHestroy.size() > 0) {
            for (int i = 0; i < listHestroy.size(); i++) {
                if (((filterStr.length() > 0) && (null != (listHestroy.get(i).search_name1)) && (listHestroy.get(i).search_name1.contains(filterStr)))) {
                    listHestroy.get(i).isduixiang = false;
                    listHestroynow.add(listHestroy.get(i));
                } else if ((null != (listHestroy.get(i).search_name)) && (listHestroy.get(i).search_name.contains(filterStr))) {
                    listHestroy.get(i).isduixiang = false;
                    listHestroynow.add(listHestroy.get(i));
                }
                //                if(listHestroy.get(i).search_name1 != null
                //                        && (listHestroy.get(i).search_name1.indexOf(filterStr.toString().toLowerCase()) != -1 || characterParser
                //                        .getSelling(listHestroy.get(i).search_name1).startsWith(
                //                                filterStr.toString()))){
                //                    listHestroy.get(i).isduixiang = false;
                //                    listHestroynow.add(listHestroy.get(i));
                //
                //                }
            }
        }
        //        for (int i=0;i<listHestroy.size();i++){
        //            Log.d("shuju",listHestroy.get(i).search_name+"::"+listHestroy.get(i).isduixiang);
        //        }
        for (int i = 0; i < listHestroynow.size(); i++) {
            Log.d("shuju", "11" + listHestroynow.get(i).search_name + "::" + listHestroynow.get(i).isduixiang);
        }
        //去重
        if (lishilist.size() > 0 || listHestroynow.size() > 0) {
            search_list.setVisibility(View.VISIBLE);
            search_no.setVisibility(View.GONE);
            search_neirong.setVisibility(View.GONE);
            search_ExpandableListViewlist.setVisibility(View.GONE);

            //去重lishilist
            for (int i = 0; i < lishilist.size(); i++) {
                for (int j = lishilist.size() - 1; j > i; j--) {
                    try {
                        if (lishilist.get(i).tabStyle.equals(lishilist.get(j).tabStyle)) {
                            lishilist.remove(j);
                        }

                    } catch (Exception ex) {

                    }
                }
            }
            //去重listHestroy
            //            for (int i = 0; i < listHestroynow.size(); i++) {
            //                for (int j = listHestroynow.size() - 1; j > i; j--) {
            //                    try {
            //                        if (listHestroynow.get(i).objId.equals(listHestroynow.get(j).objId)) {
            //                            listHestroynow.remove(j);
            //                        }
            //
            //                    }catch (Exception ex){
            //
            //                    }
            //                }
            //            }

            for (int i = 0; i < lishilist.size(); i++) {
                Log.d("shuju", lishilist.get(i).tab_name + "::" + lishilist.get(i).isduixiang);
            }
            if (adapter == null) {
                adapter = new SearchlistAdapter(this, lishilist, listHestroynow, sousuo);
                search_list.setAdapter(adapter);
                lishilist.clear();
                listHestroynow.clear();
            } else {
                adapter.changeData(lishilist, listHestroynow, sousuo);
                lishilist.clear();
                listHestroynow.clear();
            }
        } else {
            search_list.setVisibility(View.GONE);
            search_ExpandableListViewlist.setVisibility(View.GONE);
            search_no.setVisibility(View.VISIBLE);
            search_neirong.setVisibility(View.VISIBLE);
        }
    }
    class MyexpandableListAdapter extends BaseExpandableListAdapter {
        private LayoutInflater inflater;

        public MyexpandableListAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }
        @Override
        public int getGroupCount() {
            return searchResultEntity.data.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return searchResultEntity.data.get(groupPosition).list.size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return searchResultEntity.data.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return searchResultEntity.data.get(groupPosition).list.get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            GroupHolder groupHolder = null;
            //            if(convertView==null) {
            groupHolder = new GroupHolder();
            convertView = inflater.inflate(R.layout.search_group, null);
            groupHolder.name = (TextView) convertView.findViewById(R.id.search_group_name);
            groupHolder.num = (TextView) convertView.findViewById(R.id.search_group_num);
            groupHolder.more = (TextView) convertView.findViewById(R.id.search_group_more);
            groupHolder.imageView = (ImageView) convertView.findViewById(R.id.search_group_image);
            //                convertView.setTag(groupHolder);
            //            }else{
            //                groupHolder = (GroupHolder) convertView.getTag();
            //            }

            Class drawable = R.drawable.class;
            Field field = null;
            try {
                field = drawable.getField(searchResultEntity.data.get(groupPosition).style + "_1");
                int id = field.getInt(field.getName());
                groupHolder.imageView.setImageBitmap(null);
                groupHolder.imageView.setBackgroundResource(id);
            } catch (Exception e) {
                e.printStackTrace();
            }


            try {
                int keyPosition = -1;
                for (int i = 0;i<listCount.size();i++){
                    String key = "";
                    Set<String> keys =  listCount.get(i).keySet();
                    for(String key1 :keys){
                        key = key1;
                    }
                   if(searchResultEntity.data.get(groupPosition).prefix.equals(key)){
                       keyPosition = i;
                   }
                }
                groupHolder.name.setText(searchResultEntity.data.get(groupPosition).tlabel);
                if (Integer.valueOf(listCount.get(keyPosition).get(searchResultEntity.data.get(groupPosition).prefix)) > 3) {
                    groupHolder.more.setVisibility(View.VISIBLE);
                } else {
                    groupHolder.more.setVisibility(View.GONE);

                }
                Log.d("counttag",listCount.get(keyPosition).get(searchResultEntity.data.get(groupPosition).prefix)+"::"+searchResultEntity.data.get(groupPosition).prefix);
                if (Integer.valueOf(listCount.get(keyPosition).get(searchResultEntity.data.get(groupPosition).prefix)) > 50) {
                    groupHolder.num.setText("50+");
                } else {
                    groupHolder.num.setText(listCount.get(keyPosition).get(searchResultEntity.data.get(groupPosition).prefix));
                }


            } catch (Exception es) {

            }

            groupHolder.more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //                    Toast.makeText(SearchActivity.this,"点击更多",1).show();
                    Intent intent = new Intent(SearchActivity.this, SerachMoreActivity.class);
                    intent.putExtra("searchKeyWord", sousuo);
                    intent.putExtra("title", searchResultEntity.data.get(groupPosition).tlabel);
                    intent.putExtra("prefix", searchResultEntity.data.get(groupPosition).prefix);
                    startActivity(intent);


                }
            });
            return convertView;
        }

        @Override
        public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            childHolder childHolder = null;

            if (convertView == null) {
                childHolder = new childHolder();
                convertView = inflater.inflate(R.layout.search_child, null);
                childHolder.name = (TextView) convertView.findViewById(R.id.search_child_name);
                childHolder.name1 = (TextView) convertView.findViewById(R.id.search_child_name1);
                childHolder.linearLayout = (LinearLayout) convertView.findViewById(R.id.search_child);
                convertView.setTag(childHolder);
            } else {
                childHolder = (childHolder) convertView.getTag();
            }
            try {


                childHolder.name.setText(searchResultEntity.data.get(groupPosition).tlabel);
                childHolder.name1.setText(searchResultEntity.data.get(groupPosition).list.get(childPosition).name);
            } catch (Exception ex) {

            }
            childHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //                    Toast.makeText(SearchActivity.this,"点击child對象",1).show();
                    Intent intent = new Intent(SearchActivity.this, BeauInfoActivity.class);
                    intent.putExtra("web", searchResultEntity.data.get(groupPosition).list.get(childPosition).id);
                    startActivity(intent);
                }
            });
            if (childPosition >= 3) {
                childHolder.linearLayout.setVisibility(View.GONE);
                childHolder.name.setVisibility(View.GONE);
                childHolder.name1.setVisibility(View.GONE);
            } else {
                childHolder.linearLayout.setVisibility(View.VISIBLE);
                childHolder.name.setVisibility(View.VISIBLE);
                childHolder.name1.setVisibility(View.VISIBLE);
            }
            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }

        class GroupHolder {
            TextView name, num, more;
            ImageView imageView;
        }

        class childHolder {
            TextView name, name1;
            LinearLayout linearLayout;
        }
    }
}
